<template>
    <div v-loading="loading">
        <p class="title">查询余额</p>
        <el-form ref="ruleForm" :model="ruleForm" :rules="rules">
            <el-row :gutter="1">
                <el-col :span="24">
                    <el-form-item label="地址 :" prop="address" :label-width="formLabelWidth3">
                        <el-input size="small" v-model="ruleForm.address"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="1">
                <el-col :span="24">
                    <el-form-item label="" :label-width="formLabelWidth3">
                        <el-button type="primary" size="small" @click="search">查询</el-button>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
        <div class="line"></div>
        <p class="title">交易输入</p>
        <el-form class="form-label-bottom">
            <div v-for="(item,index) in showChooseLists">
                <div style="display: inline-block;width: 75%">
                    <el-row :gutter="1">
                        <el-col :span="24">
                            <el-form-item label="交易ID :" prop="txId" :label-width="formLabelWidth3">
                                <el-input size="small" v-model="item.txid"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="1">
                        <el-col :span="24">
                            <el-form-item label="地址 :" prop="index" :label-width="formLabelWidth3">
                                <el-input size="small" v-model="item.address"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="1">
                        <el-col :span="24">
                            <el-form-item label="数量 :" prop="amount" :label-width="formLabelWidth3">
                                <el-input size="small" v-model="item.amount"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="1">
                        <el-col :span="24">
                            <el-form-item label="索引 :" prop="index" :label-width="formLabelWidth3">
                                <el-input size="small" v-model="item.vout"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </div>
                <div style="display: inline-block;width: 20%;text-align: left;vertical-align: top;margin-top: 5px">
                    <el-button class="block_btn" type="primary" size="small" @click="del(index)">删除</el-button>
                    <span class="indexCode">编号: {{index + 1}}</span>
                    <!--<i class="erweima" @click="erweimaClick(index)"></i>-->
                </div>
                <div class="line"></div>
            </div>
            <el-row :gutter="1">
                <el-col :span="24">
                    <el-form-item label="" :label-width="formLabelWidth3">
                        <el-button type="primary" size="small" @click="addTransactionIn">添加交易输入</el-button>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
        <div class="line"></div>
        <el-form ref="ruleForm1" :model="ruleForm1" :rules="rules1">
            <el-row :gutter="1">
                <el-col :span="18">
                    <el-form-item label="原身份 :" :label-width="formLabelWidth3">
                        <span>{{showChooseLists.length > 0 ? showChooseLists[0].address : ''}}</span>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="1">
                <el-col :span="24">
                    <el-form-item label="操作 :" :label-width="formLabelWidth3">
                        <el-radio-group v-model="ruleForm1.operation" size="small">
                            <el-radio label="1" border>申请币天计划</el-radio>
                            <el-radio label="2" border>销毁币天领奖</el-radio>
                        </el-radio-group>
                        <br/>
                        <span style="color: red;font-size: 12px;line-height: normal;display: inline-block">申请参与计划：请花费小额utxo申请，以免损失币天。</span>
                       <br/>
                       <span style="color: red;font-size: 12px;line-height: normal;display: inline-block"> 销毁币天领奖：币将转回原地址，币天销毁，稍后奖励会发到原地址</span>                    
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="1">
                <el-col :span="24">
                    <el-form-item label="" :label-width="formLabelWidth3">
                        <el-button size="small" type="primary" style="width: 40%;" @click="showQRCode">生成待签名二维码
                        </el-button>
                        <el-button size="small" type="primary" style="width: 40%;" @click="showQRMsg">生成待签名数据
                        </el-button>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="1">
                <el-col :span="24">
                    <span class="advertisementsddd" style="color: red">请在密签2.0以上版本的高级交易中签名。</span>
                </el-col>
            </el-row>
            <el-row :gutter="1" v-if="allMsg" style="margin-top: 20px">
                <el-col :span="24">
                    <el-input size="small" v-model="allMsg" type="textarea" :rows="5"></el-input>
                </el-col>
            </el-row>
        </el-form>
        <el-dialog title="" :visible.sync="dialogFormVisible" class="dialogFormVisible">
            <el-form :model="form">
                <el-checkbox-group v-model="form.checkList" @change="handleCheckedCitiesChange"
                                   style="height: 43vh;overflow: auto">
                    <div v-for="(item,index) in form.dataList">
                        <div style="display: inline-block;width: 85%">
                            <el-row :gutter="1">
                                <el-col :span="24">
                                    <el-form-item label="交易ID :" prop="txid" :label-width="formLabelWidth2">
                                        <el-input size="small" v-model="item.txid"></el-input>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                            <el-row :gutter="1">
                                <el-col :span="24">
                                    <el-form-item label="数量 :" prop="title" :label-width="formLabelWidth2">
                                        <el-input size="small" v-model="item.amount"></el-input>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                            <el-row :gutter="1">
                                <el-col :span="24">
                                    <el-form-item label="索引 :" prop="index" :label-width="formLabelWidth2">
                                        <el-input size="small" v-model="item.vout"></el-input>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                        </div>
                        <el-checkbox class="noName"
                                     style="width: 15%;display: inline-block;vertical-align: top;text-align: center;margin-top: 5px"
                                     :label="index"></el-checkbox>
                        <div class="line"></div>
                    </div>
                </el-checkbox-group>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-checkbox :indeterminate="isIndeterminate" size="small" border v-model="checkAll"
                             @change="handleCheckAllChange">全选
                </el-checkbox>
                <el-button type="primary" size="small" @click="choose">确 定</el-button>
            </div>
        </el-dialog>
        <el-dialog
            title=""
            :visible.sync="dialogVisible"
            width="240px"
            :before-close="handleClose">
            <EWMD ref="EWMdialog" :proParm="result"></EWMD>
        </el-dialog>
        <el-dialog
            title=""
            :visible.sync="qrCodeDialog"
            width="100%"
            :before-close="qrCodeContainerDestroy">
            <div v-if="qrCodeDestroy" style="display: flex; overflow: auto;">
                <div v-for="(item,index) in showChooseLists" class="qrContainer">
                    <div :id="item.txid + index" class="qrContent"></div>
                    <div class="qrSign">输入{{index + 1}}</div>
                    <div class="line"></div>
                    <div style="padding-bottom: 10px;text-align: center">当前/总数：{{index + 1}}/{{showChooseLists.length +
                        userInfomsgs.length}}
                    </div>
                </div>
                <div v-for="(item,index) in userInfomsgs" class="qrContainer">
                    <div :id="userInfo+index" class="qrContent"></div>
                    <div class="qrSign">{{'币天奖励数据'+(index+1)+'/'+userInfomsgs.length}}</div>
                    <div class="line"></div>
                    <div style="padding-bottom: 10px;text-align: center">当前/总数：{{showChooseLists.length+(index +
                        1)}}/{{showChooseLists.length + userInfomsgs.length}}
                    </div>
                </div>
            </div>
        </el-dialog>
    </div>
</template>

<script>
    import Fetch from 'Fetch';
    import lodash from 'lodash';
    import EWMD from './ewm';
    import ElButton from "../../node_modules/element-ui/packages/button/src/button.vue";
    import ElDialog from "../../node_modules/element-ui/packages/dialog/src/component.vue";
    import ElCol from "element-ui/packages/col/src/col";

    export default {
        name: "Transaction",
        components: {
            ElCol,
            ElDialog,
            ElButton,
            EWMD
        },
        data() {
            let validUserName = (rule, value, callback) => {
                let reg = /^[|]+$/;
                if (reg.test(value)) {
                    callback(new Error('用户名不能包含|'));
                } else {
                    callback()
                }
            };
            let validTagName = (rule, value, callback) => {
                let reg = /^[|#]+$/;
                if (reg.test(value)) {
                    callback(new Error('标签名不能包含|和#'));
                } else {
                    callback()
                }
            };
            return {
                loading: false,
                formLabelWidth1: '80px',
                formLabelWidth2: '80px',
                formLabelWidth3: '72px',
                formLabelWidth4: '120px',
                ruleForm: {
                    address: '',
                },
                rules: {
                    address: [
                        {required: true, message: '请输入地址', trigger: ['blur', 'change']}
                    ],
                },
                dialogFormVisible: false,
                showChooseLists: [],
                form: {
                    dataList: [],
                    checkList: []
                },
                ruleForm1: {
                    userName: '',
                    newTag: '',
                    tags: [],
                    operation: '1',
                    range: ['1'],
                    sTime: '',
                    sTimeNowEffect: false,
                    eTime: '',
                    eTimePermanent: true
                },
                ranges: [
                    { code: '1', name: '链上留言', disable: false },
                    { code: '2', name: '属性声明', disable: false },
                    { code: '3', name: '声明认证', disable: false },
                    { code: '4', name: '贡献填报', disable: false }
                    ],
                all: false,
                rules1: {
                    userName: [
                        {required: true, message: '请输入用户名', trigger: ['blur', 'change']},
                        {validator: validUserName, trigger: ['blur', 'change']},
                        {max: 120, message: '长度不大于120个字符', trigger: ['blur', 'change']}
                    ],
                    newTag: [
                        {validator: validTagName, trigger: ['blur', 'change']},
                        {max: 120, message: '长度不大于120个字符', trigger: ['blur', 'change']}
                    ]
                },
                dialogVisible: false,
                qrcode: null,
                result: null,
                isIndeterminate: false,
                checkAll: false,
                qrCodeDialog: false,
                qrCodeDestroy: false,
                userInfo: 'userInfo',
                userInfoMsg: '',
                userInfomsgs: [],
                allMsg: ''
            }
        },
        watch: {
            all(newVal){
                if(newVal){
                    this.ruleForm1.range = [];
                    this.ranges.forEach((item)=>{
                        item.disable = true;
                    })
                }
                else {
                    this.ranges.forEach((item)=>{
                        item.disable = false;
                    })
                }
            }
        },
        props: ['proParm'],
        methods: {
            async search() {
                this.$refs['ruleForm'].validate(async (valid) => {
                    if (valid) {
                        let obj = {};
                        obj.address = this.ruleForm.address;
                        obj.cointype = 'fch';
                        this.form.checkList = [];
                        this.loading = true;
                        let result = await Fetch.Get('/wallet/listUtxo', obj);
                        if (result.code === '0') {
                            if (result.data.utxos.length > 0) {
                                this.dialogFormVisible = true;
                                this.form.dataList = result.data.utxos;
                            } else {
                                this.$message.info('该地址没有未花费的交易');
                            }
                        } else {
                            this.$message.error(result.msg);
                        }
                        this.loading = false;
                    } else {
                        return false;
                    }
                });
            },
            choose() {
                let self = this;
                let arr = [];
                self.form.checkList.forEach(item => {
                    arr.push(self.form.dataList[item]);
                });
                this.showChooseLists = this.showChooseLists.concat(arr);
                let newJson = [];
                for (const item1 of this.showChooseLists) {
                    let flag = true;
                    for (const item2 of newJson) {
                        if (item1.txid === item2.txid && item1.vout === item2.vout) {
                            flag = false;
                        }
                    }
                    if (flag) {
                        newJson.push(item1);
                    }
                }
                this.showChooseLists = newJson;
                this.dialogFormVisible = false;
            },
            del(index) {
                this.showChooseLists.splice(index, 1);
            },
            addTransactionIn() {
                this.showChooseLists.push({
                    address: '',
                    amount: '',
                    confirmations: '',
                    height: '',
                    satoshis: '',
                    txid: '',
                    vout: ''
                });
            },
            erweimaClick(index) {
                this.dialogVisible = true;
                let result = this.showChooseLists[index];
                result.dealType = 1;
                this.result = result;
                if (this.$refs.EWMdialog) {
                    this.$refs.EWMdialog.init(result);
                }
            },
            handleClose(done) {
                done();
            },
            handleCheckAllChange(val) {
                if (val) {
                    let array = [];
                    this.form.dataList.forEach((item, index) => {
                        array.push(index);
                    });
                    this.form.checkList = array;
                } else {
                    this.form.checkList = [];
                }
                this.isIndeterminate = false;
            },
            handleCheckedCitiesChange(value) {
                let checkedCount = value.length;
                this.checkAll = checkedCount === this.form.dataList.length;
                this.isIndeterminate = checkedCount > 0 && checkedCount < this.form.dataList.length;
            },
            handleCloseTag(tag) {
                this.ruleForm1.tags.splice(this.ruleForm1.tags.indexOf(tag), 1);
            },
            addTag() {
                this.$refs['ruleForm1'].validateField('newTag', phoneError => {
                    if (!phoneError) {
                        if (this.ruleForm1.newTag === '' || this.ruleForm1.tags.indexOf(this.newTag) >= 0) {
                            this.$message.error('请勿添加空值或重复值');
                            return false;
                        }
                        this.ruleForm1.tags.push(this.ruleForm1.newTag);
                    } else {
                        return false;
                    }
                });
            },
            showQRCode() {
                this.$refs['ruleForm1'].validate(async (valid) => {
                    if (valid) {
                        if (this.ruleForm1.operation === '1' || this.ruleForm1.operation === '3') {
                            let res = [];
                            let obj = {};
                            for (let i = 0; i < this.showChooseLists.length; i++) {
                                if (!obj[this.showChooseLists[i].address]) {
                                    res.push(this.showChooseLists[i]);
                                    obj[this.showChooseLists[i].address] = true;
                                }
                            }
                        }
                        // else if (this.ruleForm1.operation === '2') {
                        //     let res = [];
                        //     let obj = {};
                        //     for (let i = 0; i < this.showChooseLists.length; i++) {
                        //         if (!obj[this.showChooseLists[i].address]) {
                        //             res.push(this.showChooseLists[i]);
                        //             obj[this.showChooseLists[i].address] = true;
                        //         }
                        //     }
                        //     if (!(res.length === 2 && this.showChooseLists.length === 2)) {
                        //         this.$message.error('只能输入2个不同的交易输入地址！');
                        //         return;
                        //     }
                        // }
                        else {
                            let res = [];
                            let obj = {};
                            for (let i = 0; i < this.showChooseLists.length; i++) {
                                if (!obj[this.showChooseLists[i].address]) {
                                    res.push(this.showChooseLists[i]);
                                    obj[this.showChooseLists[i].address] = true;
                                }
                            }
                        }
                        this.qrCodeDialog = true;
                        this.qrCodeDestroy = true;

                        this.$nextTick(() => {
                            this.showChooseLists.forEach((item, index) => {
                                let qrCode = new QRCode(document.getElementById(item.txid + index), {
                                    width: 200,
                                    height: 200
                                });
                                let objCopy = Object.assign({}, item);
                                objCopy.dealType = 1;
                                delete objCopy.confirmations;
                                delete objCopy.satoshis;
                                delete objCopy.height;
                                // 复制原来的值
                                if (objCopy.dealType === 1) {
                                    objCopy['index'] = objCopy.vout.toString();
                                }
                                objCopy.amount = objCopy.amount.toString();
                                delete objCopy.vout;
                                objCopy.seq = index + 1;
                                objCopy = JSON.stringify(objCopy);
                                qrCode.makeCode(objCopy);
                            });

                            let exportInfo = {
                                address: 'FFJcrGEXirhu8JiTusR9rKw45pSbawgor4',
                                amount: '0.01',
                                dealType: 2
                            };


                            let msg = encodeFEIP11V2(this.ruleForm1.operation);
                            let userInfo = {
                                dealType: 3,
                                msg: msg,
                                msgtype: 1
                            };
                            this.userInfoMsg = JSON.stringify(userInfo);
                            this.userInfomsgs = this.userInfomsgsArry();
                            this.$nextTick(() => {
                                this.userInfomsgs.forEach((item, index) => {
                                    let userQrCode = new QRCode(document.getElementById(this.userInfo + index), {
                                        width: 200,
                                        height: 200
                                    });
                                    userQrCode.makeCode(item);
                                });
                            });
                        });
                    } else {
                        return false;
                    }
                });

            },
            userInfomsgsArry() {
                let length = this.userInfoMsg.length;
                let num = Math.ceil(length / 200);
                let array = [];
                for (let i = 0; i < num; i++) {
                    let m = this.userInfoMsg.substring(i * 200, (i + 1) * 200);
                    array.push(m);
                }
                return array;
            },
            qrCodeContainerDestroy() {
                this.qrCodeDestroy = false;
                this.qrCodeDialog = false;
            },
            showQRMsg() {
                this.$refs['ruleForm1'].validate(async (valid) => {
                    if (valid) {

                        if (this.ruleForm1.operation === '1' || this.ruleForm1.operation === '3') {
                            let res = [];
                            let obj = {};
                            for (let i = 0; i < this.showChooseLists.length; i++) {
                                if (!obj[this.showChooseLists[i].address]) {
                                    res.push(this.showChooseLists[i]);
                                    obj[this.showChooseLists[i].address] = true;
                                }
                            }
                        }
                        // else if (this.ruleForm1.operation === '2') {
                        //     let res = [];
                        //     let obj = {};
                        //     for (let i = 0; i < this.showChooseLists.length; i++) {
                        //         if (!obj[this.showChooseLists[i].address]) {
                        //             res.push(this.showChooseLists[i]);
                        //             obj[this.showChooseLists[i].address] = true;
                        //         }
                        //     }
                        //     if (!(res.length === 2 && this.showChooseLists.length === 2)) {
                        //         this.$message.error('只能输入2个不同的交易输入地址！');
                        //         return;
                        //     }
                        // }
                        else {
                            let res = [];
                            let obj = {};
                            for (let i = 0; i < this.showChooseLists.length; i++) {
                                if (!obj[this.showChooseLists[i].address]) {
                                    res.push(this.showChooseLists[i]);
                                    obj[this.showChooseLists[i].address] = true;
                                }
                            }
                        }


                        this.allMsg = '';
                        let arr = [];

                        let exportInfo = {
                            address: 'FFJcrGEXirhu8JiTusR9rKw45pSbawgor4',
                            amount: '0.01',
                            dealType: 2
                        };
                        let msg = encodeFEIP11V2(this.ruleForm1.operation);
                        let userInfo = {
                            dealType: 3,
                            msg: msg,
                            msgtype: 1
                        };

                        let inputArr = [];
                        this.showChooseLists.forEach((item, index) => {
                            let objCopy = Object.assign({}, item);
                            delete objCopy.confirmations;
                            delete objCopy.satoshis;
                            delete objCopy.height;
                            objCopy.dealType = 1;
                            // 复制原来的值
                            if (objCopy.dealType === 1) {
                                objCopy['index'] = objCopy.vout.toString();
                            }
                            objCopy.amount = objCopy.amount.toString();
                            delete objCopy.vout;
                            objCopy.seq = index + 1;
                            inputArr.push(objCopy);
                        });
                        arr = arr.concat(inputArr, [userInfo]);
                        this.allMsg = JSON.stringify(arr);
                    } else {
                        return false;
                    }
                });
            }
        }
    }
</script>

<style scoped lang="less">

    .title {
        font-weight: bold;
    }

    .advertisementsddd {
        color: #3a8ee6;
        font-size: 14px;
    }

    /deep/ .el-form-item__label {
        padding: 0 5px 0 0;
    }

    /deep/ .el-radio__label {
        padding-left: 5px;
    }

    .block_btn {
        margin-left: 10px;
        background-color: red;
        display: block;
        border: solid 1px red;
    }

    .noName /deep/ .el-checkbox__label {
        display: none
    }

    .indexCode {
        display: inline-block;
        height: 30px;
        margin-top: 32px;
        margin-left: 20px;
        line-height: 32px;
        font-size: 12px;
    }

    .erweima {
        width: 30px;
        height: 30px;
        background: url("../../static/images/erweima.png");
        background-size: cover;
        display: block;
        margin-top: 32px;
        margin-left: 20px;
    }

    .line {
        width: 100%;
        height: 5px;
        margin: 5px 0;
        background-color: #e4e7ed;
        z-index: 1;
    }

    .el-tag {
        margin-right: 10px;
    }

    .el-radio {
        margin-right: 10px;
        padding: 8px 5px 0 5px;
    }

    .el-radio.is-bordered + .el-radio.is-bordered {
        margin-right: 10px;
        padding: 8px 5px 0 5px;
        margin-left: 0;
    }

    .qrContainer {
        display: inline-block;
    }

    .qrContent {
        display: inline-block;
        width: 200px;
        height: 200px;
        margin: 10px;
    }

    .qrSign {
        width: 200px;
        height: 30px;
        line-height: 30px;
        text-align: center;
    }

</style>
